<?php

namespace app\admin\service\cms;

use tmcore\base\BaseService;
use app\common\model\article\Article;
use app\common\model\article\ArticleCate;
use app\admin\service\ExportService;
use tmcore\services\ImportExcelService;

/**
 * 文章管理服务类
 */
class ArticleService extends BaseService
{
    /**
     * 获取文章列表
     * @return array
     */
    public static function getList(): array
    {
        // 搜索条件
        $searchParam = [
            '=' => ['status'],
            '%like%' => ['title']
        ];

        // 分类筛选
        $cate_id = request()->param('cate_id');
        if($cate_id) {
            $cateIds = ArticleCate::where(['pid' => $cate_id])->column('id');
            if($cateIds) {
                array_push($cateIds, intval($cate_id));
                $extend_where = ['cate_id', 'in', $cateIds];
            } else {
                $extend_where = ['cate_id', '=', $cate_id];
            }
        } else {
            $extend_where = [];
        }

        $where = self::getSearchData($searchParam, $extend_where);

        // 返回分页数据
        $list = Article::page($where, self::getPageData(), 'id,title,cate_id,image,author,actual_hits,init_hits,sort,status,create_time', ['sort' => 'desc', 'id' => 'desc'], ['cate_name', 'hits', 'status_desc']);

        foreach ($list['list'] as &$item) {
            $item['image'] = get_file_url($item['image']);
            $item['link'] = '/pages/cms/article_detail?id=' . $item['id'];
        }
        return $list;
    }

    /**
     * 添加文章
     * @param array $params
     * @return bool
     */
    public static function add(array $params)
    {
        return Article::add([
            'cate_id' => $params['cate_id'],
            'title' => $params['title'],
            'desc' => $params['desc'] ?? '',
            'summary' => $params['summary'] ?? '',
            'image' => $params['image'] ?? '',
            'author' => $params['author'] ?? '',
            'content' => $params['content'] ?? '',
            'sort' => $params['sort'] ?? 0,
            'init_hits' => $params['init_hits'] ?? 0,
            'is_recommend' => $params['is_recommend'],
            'status' => $params['status'],
        ]);
    }


    /**
     * 编辑文章
     * @param array $params
     * @return bool
     */
    public static function edit(array $params): bool
    {
        return Article::edit([
            'cate_id' => $params['cate_id'],
            'title' => $params['title'],
            'desc' => $params['desc'] ?? '',
            'summary' => $params['summary'] ?? '',
            'image' => $params['image'] ?? '',
            'author' => $params['author'] ?? '',
            'content' => $params['content'] ?? '',
            'sort' => $params['sort'] ?? 0,
            'init_hits' => $params['init_hits'] ?? 0,
            'is_recommend' => $params['is_recommend'],
            'status' => $params['status'],
        ], $params['id']);
    }


    /**
     * 删除文章
     * @param array $params
     * @return bool
     */
    public static function delete(array $params)
    {
        return Article::del($params['id']);
    }

    /**
     * 查看文章详情
     * @param $params
     * @param bool $is_inc
     * @return array
     */
    public static function detail($params, $is_inc = false): array
    {
        $article = Article::where(['id' => $params['id']])
            ->findOrEmpty();
        if ($article->isEmpty()) return [];

        // 点击量自增
        if ($is_inc) $article->inc('actual_hits', 1)->update();

        return $article->append(['hits'])->toArray();
    }

    /**
     * 更改文章状态
     * @param array $params
     * @return bool
     */
    public static function updateStatus(array $params)
    {
        return Article::edit([
            'status' => $params['status']
        ], $params['id']);
    }

    /**
     * 导出文章
     * @param array $params
     * @param array $adminInfo
     * @return array|bool
     */
    public static function export(array $params, array $adminInfo)
    {
        // 搜索条件
        $searchParam = [
            '=' => ['status'],
            '%like%' => ['title']
        ];

        // 分类筛选
        $cate_id = request()->param('cate_id');
        if($cate_id) {
            $cateIds = ArticleCate::where(['pid' => $cate_id])->column('id');
            if($cateIds) {
                array_push($cateIds, intval($cate_id));
                $extend_where = ['cate_id', 'in', $cateIds];
            } else {
                $extend_where = ['cate_id', '=', $cate_id];
            }
        } else {
            $extend_where = [];
        }

        $where = self::getSearchData($searchParam, $extend_where, $params);
        $list = Article::exportPage(self::getExportData($params), $where, self::getPageData(), "id,title,cate_id,image,author,actual_hits,init_hits,sort,is_recommend,status,create_time", ['sort' => 'desc', 'id' => 'desc'],  ['hits', 'status_desc', 'recommend_desc']);
        // 循环数据
        $cate_list = ArticleCate::column('name','id');
        foreach ($list['list'] as &$item) {
            $item['cate_name'] = $item['cate_id']?$cate_list[$item['cate_id']]:'';
        }

        $filename = $params['file_name'] ?? '文章列表';
        $header = [
            'id' => 'ID',
            'title' => '标题',
            'cate_name' => '栏目',
            'image' => '封面',
            'author' => '作者',
            'hits' => '点击量',
            'init_hits' => '初始点击量',
            'sort' => '排序',
            'recommend_desc' => '是否推荐',
            'status_desc' => '状态',
            'create_time' => '创建时间',
        ];
        $res = ExportService::exportExcel($list, $filename, $header, ['name' => $adminInfo['name'], 'id' => $adminInfo['id']]);

        if ($res === false) {
            return self::setError(ExportService::getError());
        } else {
            return $res;
        }
    }

    /**
     * 导入文章
     * @param array $params
     * @param array $adminInfo
     * @return array|bool
     */
    public static function import(array $params, array $adminInfo)
    {
        $list = ImportExcelService::importExcel('file');

        $key_arr = [
            'title' => 0,
            'cate_id' => 1,
            'image' => 2,
            'desc' => 3,
            'summary' => 4,
            'author' => 5,
            'content' => 6,
            'init_hits' => 7,
            'sort' => 8,
            'is_recommend' => 9,
            'status' => 10,
        ];

        ImportExcelService::listForeach($list['data'], $key_arr, function ($value, $key, $column_name, $row_count) use ($params) {
            if (!$value && $column_name == 'title') ImportExcelService::setError($key, $column_name, $row_count, $key . '不可为空');
            if (!$value && $column_name == 'cate_id') ImportExcelService::setError($key, $column_name, $row_count, $key . '不可为空');
            if (!$value && $column_name == 'image') ImportExcelService::setError($key, $column_name, $row_count, $key . '不可为空');
        }, function ($value, $key) use ($params) {
            $data = [
                'title' => $value[0] ?? '',
                'cate_id' => $value[1] ?? 0,
                'image' => $value[2] ?? '',
                'desc' => $value[3] ?? '',
                'summary' => $value[4] ?? '',
                'author' => $value[5] ?? '',
                'content' => $value[6] ?? '',
                'init_hits' => $value[7] ?? 0,
                'sort' => $value[8] ?? 0,
                'is_recommend' => $value[9] ?? 0,
                'status' => $value[10] ?? 1,
            ];
            ImportExcelService::setSuccess($data);
        });

        // 批量增加数据
        (new Article)->saveAll(ImportExcelService::$createData);

        return ImportExcelService::getImportResult();
    }
}